package com.hornsun.client.personalPage.service;

import com.google.common.base.Preconditions;
import com.hornsun.domain.dbo.Address;
import com.hornsun.domain.dto.AddressDTO;
import com.hornsun.repository.AddressRepository;
import com.hornsun.repository.mapper.AddressMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by 编译中... on 2018/5/12.
 */
@Service
public class AddressService {
    @Resource
    private AddressRepository addressRepository;

    @Resource
    private AddressMapper addressMapper;

    /**
     * 地址串转地址
     * @param addressDTO
     * @return
     */
    public Address toAddress(AddressDTO addressDTO){
        Preconditions.checkNotNull(addressDTO.getDetailaddress());
        Preconditions.checkNotNull(addressDTO.getPhone());
        Preconditions.checkNotNull(addressDTO.getRegion());
        Preconditions.checkNotNull(addressDTO.getUsername());
        Preconditions.checkNotNull(addressDTO.isChecked());
        String[]  region = addressDTO.getRegion();
        String location = "";
        for(int i=0;i<region.length;i++){
            location+=region[i];
        }
        location+=addressDTO.getDetailaddress();
        Address address = new Address();
        address.setRecipient(addressDTO.getUsername());
        address.setIsDefault(addressDTO.isChecked());
        address.setLocation(location);
        address.setPhone(addressDTO.getPhone());
        return address;
    }

    public Address getPayAddress(String openid){
        List<Address> addresses =  addressRepository.getAddressesByOpenid(openid);
        if (addresses.isEmpty()||addresses.size()==0){
            return null;
        }
        List<Address> defaultAddresses = addressRepository.getDefaultAddress(openid);
        if (defaultAddresses.isEmpty()||defaultAddresses.size()==0){
           return addressMapper.getPioneerAddress(openid);
        }
        return defaultAddresses.get(0);
    }
}
